package com.cskaoyan.order.biz.handler;

import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dto.CartProductDto;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private GlobalIdGeneratorUtil globalIdGeneratorUtil;

    @Override
    public boolean isAsync() {
        return false;
    }

    /**
     * @descriptio: TODO
     * @params: [context]
     * @return: boolean
     * @author: HeXiangZhi
     * @date: 2022/12/3 15:26
     */
    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        Order order = new Order();
        //String orderId = UUID.randomUUID().toString();
        // 以后可以用 全局id生成器（发号器）
        String orderId = globalIdGeneratorUtil.getNextSeq("orderId", 1);
        order.setOrderId(orderId);
        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getBuyerNickName());
        order.setPayment(createOrderContext.getOrderTotal());
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);

        int effectedRows = orderMapper.insert(order);
        if (effectedRows < 1) {
            throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(), OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
        }


        // 插入订单商品关联表
        List<Long> buyProductIds = new ArrayList<>();

        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            OrderItem orderItem = new OrderItem();
            //String orderItemId = UUID.randomUUID().toString();
            String orderItemId = globalIdGeneratorUtil.getNextSeq("orderItemId", 1);
            orderItem.setId(orderItemId);
            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(orderId);
            orderItem.setNum(cartProductDto.getProductNum().intValue());
            orderItem.setPrice(cartProductDto.getSalePrice().doubleValue());
            orderItem.setTitle(cartProductDto.getProductName());
            orderItem.setPicPath(cartProductDto.getProductImg());
            // double类型可以调用multiply
            BigDecimal total = cartProductDto.getSalePrice().multiply(new BigDecimal(cartProductDto.getProductNum()));
            orderItem.setTotalFee(total.doubleValue());
            // 库存锁定状态 1库存已锁定 2库存已释放 3-库存减扣成功
            orderItem.setStatus(1);
            buyProductIds.add(cartProductDto.getProductId());

            int insert = orderItemMapper.insert(orderItem);
            if (insert < 1) {
                throw new BizException(OrderRetCode.INIT_ORDER_EXCEPTION.getCode(), OrderRetCode.INIT_ORDER_EXCEPTION.getMessage());
            }


        }

        createOrderContext.setOrderId(orderId);
        createOrderContext.setBuyProductIds(buyProductIds);

        return true;
    }

}
